import { ApiOutlined } from '@ant-design/icons';
import React, { useEffect, useState } from 'react';
import {
  BrowserRouter as Routers,
  useRoutes,
  useNavigate,
  useLocation,
  RouteObject
} from "react-router-dom";

import { Drawer, Dropdown, Menu, Select, Spin, Tag, Button, Layout } from 'antd';
import { IRouterConfigPlusItem } from './api/interface/baseInterface';
import { formatRoute, getDefaultOpenKeys, routerConfigPlus } from './routerConfig';
import SubMenu from 'antd/lib/menu/SubMenu';
import { getParam, obj2UrlParam, parseParam2Obj } from './util';
import { getAppHeaderConfig, getAppMenu, getCustomDialog, userLogout } from './api/kubeflowApi';
import { IAppHeaderItem, IAppMenuItem, ICustomDialog } from './api/interface/kubeflowInterface';
import {
  AppstoreOutlined,
  DownOutlined,
  LeftOutlined,
  RightOutlined,
  TranslationOutlined,
  MenuFoldOutlined,
  MenuUnfoldOutlined,
  UserOutlined,
  SettingOutlined,
  DatabaseOutlined,
  CodeOutlined,
  CloudServerOutlined,
  CloudOutlined
} from '@ant-design/icons';
import Cookies from 'js-cookie';
import { handleTips } from './api';
import globalConfig from './global.config';
import i18nEn from './images/i18nEn.svg';
import { useTranslation, Trans } from 'react-i18next';

const userName = Cookies.get('myapp_username');

const { Header, Sider, Content } = Layout;

const RouterConfig = (config: RouteObject[]) => {
  let element = useRoutes(config);
  return element;
};

const getRouterMap = (routerList: IRouterConfigPlusItem[]): Record<string, IRouterConfigPlusItem> => {
  const res: Record<string, IRouterConfigPlusItem> = {};
  const queue = [...routerList];
  while (queue.length) {
    const item = queue.shift();
    if (item) {
      res[item?.path || ''] = item;
      if (item?.children && item.children.length) {
        queue.push(...item.children);
      }
    }
  }
  return res;
};

const getValidAppList = (config: IRouterConfigPlusItem[]) => config.filter(item => !!item.name && !item.hidden);

// 顶级菜单图标映射
const menuIconMap: Record<string, React.ReactNode> = {
  'project-space': <AppstoreOutlined />,
  'data-asset': <DatabaseOutlined />,
  'online-dev': <CodeOutlined />,
  'model-training': <CloudServerOutlined />,
  'service': <CloudOutlined />,
  'default': <AppstoreOutlined />,
  'flowise': <ApiOutlined />,
  'chatflows': <AppstoreOutlined />,//<HierarchyOutlined />,
  'agentflows': <AppstoreOutlined />,//<UsersGroupOutlined />, 
  'tools': <AppstoreOutlined />,//<ToolOutlined />,
  'credentials': <AppstoreOutlined />,//<LockOutlined />,
  'variables': <AppstoreOutlined />,//<VariableOutlined />,
  'apikey': <AppstoreOutlined />,//<KeyOutlined />,
};

// 允许的顶级菜单名称列表
//const allowedTopMenus = ['group', 'data', 'dev', 'train', 'service'];


const allowedTopMenus = ['model_home','model_management', 'model_service', 'model_dev', 'dev', 'flowise'];
const getMenuIcon = (menu: IRouterConfigPlusItem | IAppMenuItem) => {
  if (React.isValidElement(menu.icon)) {
    return menu.icon;
  }
  if (Object.prototype.toString.call(menu.icon) === '[object String]' && (menu.icon as string).trim() !== '') {
    return <div className="icon-custom svg16 mr8" dangerouslySetInnerHTML={{ __html: menu.icon as string }}></div>;
  }
  const key = menu.name || 'default';
  return menuIconMap[key] || menuIconMap['default'];
};

interface IProps { }

const AppWrapper = (props: IProps) => {
  const [collapsed, setCollapsed] = useState(false);
  const [openKeys, setOpenKeys] = useState<string[]>([]);
  const [currentNavList, setCurrentNavList] = useState<IRouterConfigPlusItem[]>([]);
  const [sourceAppList, setSourceAppList] = useState<IRouterConfigPlusItem[]>([]);
  const [sourceAppMap, setSourceAppMap] = useState<Record<string, IRouterConfigPlusItem>>({});
  const [CurrentRouteComponent, setCurrentRouteComponent] = useState<any>();
  const [isMenuCollapsed, setIsMenuCollapsed] = useState(false);
  const [isShowSlideMenu, setIsShowSlideMenu] = useState(true);
  const [imgUrlProtraits, setImgUrlProtraits] = useState('');
  const [customDialogVisable, setCustomDialogVisable] = useState(false);
  const [customDialogInfo, setCustomDialogInfo] = useState<ICustomDialog>();
  const [headerConfig, setHeaderConfig] = useState<IAppHeaderItem[]>([]);
  const [navSelected, setNavSelected] = useState<string[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [selectedKeys, setSelectedKeys] = useState<string[]>([]);
  const isShowNav = getParam('isShowNav');

  const navigate = useNavigate();
  const location = useLocation();
  const { t, i18n } = useTranslation();
  const { pathname } = location;

  // 修改 selectedKeys 设置逻辑
  useEffect(() => {
    console.log(`当前路径: ${pathname}`);
    console.log('当前路由映射:', sourceAppMap);

    // 查找与当前路径完全匹配的菜单项
    let matchedKey = pathname;
    if (sourceAppMap[pathname]) {
      setSelectedKeys([pathname]);
    } else {
      // 如果没有完全匹配，尝试匹配父级路径
      const pathSegments = pathname.split('/').filter(Boolean);
      for (let i = pathSegments.length; i > 0; i--) {
        const parentPath = '/' + pathSegments.slice(0, i).join('/');
        if (sourceAppMap[parentPath]) {
          setSelectedKeys([parentPath]);
          break;
        }
      }
    }
  }, [pathname, sourceAppMap]);

  useEffect(() => {
    setImgUrlProtraits(require('./images/male.png'));
    setIsLoading(true);

    getAppMenu().then(res => {
      try {
        const remoteRoute = res.data;
        console.log('获取到的菜单数据:', remoteRoute);
        remoteRoute.forEach((item: IAppMenuItem, index: number) => {
          console.log(`菜单项 ${index}:`, {
            name: item.name,
            title: item.title,
            path: item.path,
            hidden: item.hidden
          });
        });

        const cleanedRemoteRoute = remoteRoute.map((item: IAppMenuItem) => {
          if (!item.title || item.title.trim() === '') {
            item.title = item.name || '未命名菜单';
          }
          if (!item.icon || (typeof item.icon === 'string' && item.icon.trim() === '')) {
            const defaultIcon = '<svg viewBox="0 0 1024 1024" width="1em" height="1em"><path d="M880 112H144c-17.7 0-32 14.3-32 32v736c0 17.7 14.3 32 32 32h736c17.7 0 32-14.3 32-32V144c0-17.7-14.3-32-32-32zM698.5 523.3l-10.3 22.7H536c-4.4 0-8 3.6-8 8v128c0 4.4 3.6 8 8 8h152.2c4.4 0 8-3.6 8-8v-22.7l10.3 22.7c1.6 3.4 5 5.3 8.5 5.3h84c5.8 0 9.4-6.3 6.5-11.5l-95.6-209.4c-3.8-8.4-12.1-13.8-21.4-13.8h-48.2c-9.2 0-17.6 5.4-21.4 13.8L524.2 683.9c-2.9 5.2 0.7 11.5 6.5 11.5h84c3.5 0 6.9-1.9 8.5-5.3l68.1-149.8h7.2z" fill="currentColor"/></svg>';
            item.icon = defaultIcon;
          }
          if (item.children && Array.isArray(item.children)) {
            item.children = item.children.filter((child: IAppMenuItem) =>
              child && child.title && child.title.trim() !== ''
            ).map((child: IAppMenuItem) => {
              if (!child.title || child.title.trim() === '') {
                child.title = child.name || '未命名子菜单';
              }
              if (!child.icon || (typeof child.icon === 'string' && child.icon.trim() === '')) {
                const defaultIcon = '<svg viewBox="0 0 1024 1024" width="1em" height="1em"><path d="M880 112H144c-17.7 0-32 14.3-32 32v736c0 17.7 14.3 32 32 32h736c17.7 0 32-14.3 32-32V144c0-17.7-14.3-32-32-32zM698.5 523.3l-10.3 22.7H536c-4.4 0-8 3.6-8 8v128c0 4.4 3.6 8 8 8h152.2c4.4 0 8-3.6 8-8v-22.7l10.3 22.7c1.6 3.4 5 5.3 8.5 5.3h84c5.8 0 9.4-6.3 6.5-11.5l-95.6-209.4c-3.8-8.4-12.1-13.8-21.4-13.8h-48.2c-9.2 0-17.6 5.4-21.4 13.8L524.2 683.9c-2.9 5.2 0.7 11.5 6.5 11.5h84c3.5 0 6.9-1.9 8.5-5.3l68.1-149.8h7.2z" fill="currentColor"/></svg>';
                child.icon = defaultIcon;
              }
              return child;
            });
          }
          return item;
        });

        const dynamicRoute = formatRoute([...cleanedRemoteRoute]);
        const tarRoute = [...dynamicRoute, ...routerConfigPlus];
        console.log('最终路由配置:', tarRoute);

        const tarRouteMap = getRouterMap(tarRoute);
        setSourceAppList(tarRoute);
        setSourceAppMap(tarRouteMap);
        const defaultOpenKeys = getDefaultOpenKeys(tarRoute);
        setOpenKeys(defaultOpenKeys);
        setCurrentRouteComponent(() => () => RouterConfig(tarRoute as RouteObject[]));
        setIsLoading(false);
      } catch (err) {
        console.error('处理菜单数据出错', err);
        setIsLoading(false);
      }
    }).catch(err => {
      console.error('获取菜单数据出错', err);
      setIsLoading(false);
    });

    getAppHeaderConfig().then(res => {
      const headerData = res.data;
      setHeaderConfig(headerData);
    }).catch(err => {
      console.error('获取头部配置出错', err);
    });
  }, []);

  useEffect(() => {
    if (sourceAppList.length && Object.keys(sourceAppMap).length) {
      handleCurrentRoute(sourceAppMap, getValidAppList(sourceAppList));
    }
  }, [location, sourceAppList, sourceAppMap]);

  useEffect(() => {
    const controller = new AbortController();
    const url = encodeURIComponent(location.pathname);
    getCustomDialog(url, controller.signal).then(res => {
      setCustomDialogInfo(res.data);
      setCustomDialogVisable(res.data.hit);
    }).catch(err => {
      console.log(err);
    });
    return () => {
      controller.abort();
    };
  }, [location]);

  const handleCurrentRoute = (appMap: Record<string, IRouterConfigPlusItem>, appList: IRouterConfigPlusItem[]) => {
    const { pathname } = location;
    const [_, stLevel, edLevel] = pathname.split('/');
    const stLevelApp = appMap[`/${stLevel}`];
    let currentNavKey = "";
    if (stLevelApp && stLevelApp.isSingleModule) {
      currentNavKey = `/${stLevel}/${edLevel}`;
    } else {
      currentNavKey = `/${stLevel}`;
    }

    let topNavAppList = appList;
    if (stLevelApp && stLevelApp.isSingleModule) {
      topNavAppList = stLevelApp.children || [];
    }

    setCurrentNavList(topNavAppList);
    setNavSelected([currentNavKey]);
    setIsShowSlideMenu(stLevelApp && !stLevelApp.isCollapsed);
  };

  const handleClickNav = (app: IRouterConfigPlusItem, subPath?: string) => {
    if (!app) return;

    if (app.path === '/') {
      navigate(app.path || '/');
    } else if (app.menu_type === 'iframe' && app.path) {
      navigate(app.path);
    } else if (app.menu_type === 'out_link' && app.url) {
      window.open(app.url || '#', '_blank');
    } else if (app.menu_type === 'in_link' && app.path) {
      window.open(app.url || '#', '_blank');
    } else {
      const currentApp = sourceAppMap[subPath || ''];
      let currentItem = subPath ? currentApp : app;

      while (currentItem && currentItem.children?.length) {
        currentItem = currentItem.children[0];
      }

      if (currentItem && currentItem.path) {
        let appMenuPath = currentItem.path;
        navigate(appMenuPath);
      }
    }
  };

  const filterValidMenuItem = (item: IRouterConfigPlusItem | IAppMenuItem): boolean => {
    if (!item) return false;
    const hasBasicProps = Boolean(item.title && item.title.trim() !== '' && item.path && item.path.trim() !== '');
    const isNotHidden = Boolean(item.hidden === false || item.hidden === undefined || Number(item.hidden) === 0);
    return hasBasicProps && isNotHidden;
  };

  const getFilteredMenuItems = () => {
    console.log('源菜单列表:', sourceAppList);
    const filtered = sourceAppList.filter(app => {
      if (!app || !app.name) return false;

      console.log(`菜单项 ${app.name}:`, {
        name: app.name,
        title: app.title,
        path: app.path,
        hidden: app.hidden,
        isInAllowedList: allowedTopMenus.includes(app.name)
      });

      const isAllowedTopMenu = allowedTopMenus.includes(app.name);
      const isValidMenuItem = filterValidMenuItem(app);
      return isAllowedTopMenu && isValidMenuItem;
    });

    console.log('过滤后的菜单列表:', filtered);
    return filtered;
  };

  const renderSideMenu = () => {
    if (!sourceAppList.length) {
      return null;
    }

    const filteredMenuItems = getFilteredMenuItems();

    return (
      <Menu
        mode="inline"
        selectedKeys={selectedKeys}
        openKeys={collapsed ? [] : openKeys}
        onOpenChange={(keys) => setOpenKeys(keys)}
        style={{ height: '100%', borderRight: 0 }}
        theme="dark"
        inlineCollapsed={collapsed}
        defaultOpenKeys={openKeys}
      >
        {filteredMenuItems.map(app => {
          const validChildren = app.children?.filter(filterValidMenuItem) || [];

          if (validChildren.length > 0) {
            return (
              <SubMenu
                key={app.path}
                icon={getMenuIcon(app)}
                title={app.title}
                popupClassName="side-menu-popup"
                onTitleClick={() => collapsed && handleClickNav(app)}
              >
                {validChildren.map(child => {
                  const validGrandChildren = child.children?.filter(filterValidMenuItem) || [];

                  if (validGrandChildren.length > 0) {
                    return (
                      <SubMenu
                        key={child.path}
                        title={child.title}
                        icon={getMenuIcon(child)}
                        popupClassName="side-menu-popup"
                      >
                        {validGrandChildren.map(grandChild => (
                          <Menu.Item
                            key={grandChild.path}
                            onClick={() => handleClickNav(grandChild)}
                            disabled={Boolean(grandChild.disable)}
                            icon={getMenuIcon(grandChild)}
                            title={grandChild.title}
                          >
                            {grandChild.title}
                          </Menu.Item>
                        ))}
                      </SubMenu>
                    );
                  }

                  return (
                    <Menu.Item
                      key={child.path}
                      onClick={() => handleClickNav(child)}
                      disabled={Boolean(child.disable)}
                      icon={getMenuIcon(child)}
                      title={child.title}
                    >
                      {child.title}
                    </Menu.Item>
                  );
                })}
              </SubMenu>
            );
          }

          return (
            <Menu.Item
              key={app.path}
              onClick={() => handleClickNav(app)}
              disabled={Boolean(app.disable)}
              icon={getMenuIcon(app)}
              title={app.title}
            >
              {app.title}
            </Menu.Item>
          );
        })}
      </Menu>
    );
  };

  const renderNavTopMenu = () => {
    return currentNavList.map((app) => {
      if (!!app.hidden) {
        return null;
      }
      if (app.isSingleModule || app.isDropdown) {
        return (
          <Menu.SubMenu
            key={app.path}
            title={
              <div className="star-topnav-submenu" onClick={() => {
                if (app.isDropdown) {
                  return;
                }
                handleClickNav(app);
              }}>
                {Object.prototype.toString.call(app.icon) === '[object String]' ? (
                  <div className="icon-custom" dangerouslySetInnerHTML={{ __html: app.icon }}></div>
                ) : (
                  app.icon
                )}
                <div className="mainapp-topmenu-name">{app.title}</div>
                <DownOutlined className="ml8" />
              </div>
            }
          >
            {(app.children || []).map(subapp => (
              <Menu.Item
                key={subapp.path}
                onClick={() => {
                  // 确保iframe类型的菜单项能正确跳转
                  if (subapp.menu_type === 'iframe' && subapp.path) {
                    navigate(subapp.path);
                  } else {
                    handleClickNav(subapp, subapp.path);
                  }
                }}
              >
                <div className="d-f ac">
                  {Object.prototype.toString.call(subapp.icon) === '[object String]' ? (
                    <div className="icon-custom" dangerouslySetInnerHTML={{ __html: subapp.icon }}></div>
                  ) : (
                    subapp.icon
                  )}
                  <div className="pl8">{subapp.title}</div>
                </div>
              </Menu.Item>
            ))}
          </Menu.SubMenu>
        );
      }
      return (
        <Menu.Item
          key={app.path}
          onClick={() => handleClickNav(app)}
        >
          {Object.prototype.toString.call(app.icon) === '[object String]' ? (
            <div className="icon-custom" dangerouslySetInnerHTML={{ __html: app.icon }}></div>
          ) : (
            app.icon
          )}
          <div className="mainapp-topmenu-name">{app.title}</div>
        </Menu.Item>
      );
    });
  };

  const renderSingleModule = () => {
    const { pathname } = location;
    const [_, stLevel] = pathname.split('/');
    const stLevelApp = sourceAppMap[`/${stLevel}`];
    if (stLevelApp && stLevelApp.isSingleModule) {
      return <Tag key={`tag-${stLevelApp.path}`} color="#1672fa">{stLevelApp.title}</Tag>;
    }
    return null;
  };

  return (
    <Layout style={{ minHeight: '100vh' }}>
      <Header style={{
        background: '#041b29',
        padding: 0,
        height: 64,
        lineHeight: '64px',
        position: 'fixed',
        zIndex: 1000,
        width: '100%',
        boxShadow: '0 1px 4px rgba(0,0,0,0.1)'
      }}>
        <div className="d-f jc-sb" style={{ height: '100%' }}>
          <div className="d-f ac" style={{ gap: 12 }}>
            <img
              className="cp"
              onClick={() => { navigate('/', { replace: true }); }}
              style={{ height: 32 }}
              src={globalConfig.appLogo}
              alt="logo"
            />
            <h2 style={{ color: 'white', margin: 0, lineHeight: 1 }}>模型算法服务</h2>
            <Button
              type="text"
              icon={collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
              onClick={() => setCollapsed(!collapsed)}
            />
          </div>
            
          {/* <div className="star-topmenu">
            <Menu mode="horizontal" selectedKeys={navSelected}>
              {renderNavTopMenu()}
              <Menu.Item key="/flowise" onClick={() => navigate('/flowise')}>
                <ApiOutlined style={{ fontSize: 18 }} />
                <div className="mainapp-topmenu-name">Flowise</div>
              </Menu.Item> 
            </Menu>
          </div> */}

          <div className="d-f ac plr16 h100">
            {/* {headerConfig.map((config, index) => {
              if (config.icon) {
                return (
                  <a
                    key={`header_config_${config.text || index}`}
                    href={config.link}
                    target="_blank"
                    className="mr12 d-f ac"
                    rel="noreferrer"
                  >
                    <span className="pr4">{config.text}</span>
                    <span className="icon-custom" dangerouslySetInnerHTML={{ __html: config.icon }}></span>
                  </a>
                );
              } else if (config.pic_url) {
                return (
                  <a
                    key={`header_config_${config.text || index}`}
                    href={config.link}
                    target="_blank"
                    className="mr12 d-f ac"
                    rel="noreferrer"
                  >
                    <span className="pr4">{config.text}</span>
                    <img style={{ height: 30 }} src={config.pic_url} alt="" />
                  </a>
                );
              }
              return null;
            })} */}
            <Dropdown overlay={(
              <Menu>
                <Menu.Item onClick={() => navigate('/user')}>
                  {t("用户中心")}
                </Menu.Item>
                <Menu.Item onClick={() => {
                  Cookies.remove('myapp_username');
                  handleTips.userlogout();
                }}>
                  {t("退出登录")}
                </Menu.Item>
              </Menu>
            )}>
              <div className="d-f ac cp">
                <img
                  className="mr8"
                  style={{ borderRadius: 200, height: 32 }}
                  src={imgUrlProtraits}
                  onError={() => setImgUrlProtraits(require('./images/male.png'))}
                  alt="img"
                />
                <span>{userName}</span>
              </div>
            </Dropdown>
          </div>
        </div>
      </Header>
      <div style={{ height: 64 }}></div>
      <Layout style={{ height: 'calc(100vh - 64px)', overflow: 'hidden' }}>
        {!collapsed && (
          <Sider
            width={232}
            trigger={null}
            className="site-sider"
            style={{
              background: '#20333a',
              height: 'calc(100vh - 64px)',
              position: 'fixed',
              top: 64,
              left: 0,
              transition: 'all 0.2s',
              overflowY: 'auto',
              overflowX: 'hidden',
              boxShadow: '2px 0 8px rgba(0,0,0,0.1)',
              zIndex: 999,
              display: 'flex',
              flexDirection: 'column'
            }}
          >
            <div
              className="menu-collapse-toggle"
              onClick={() => setCollapsed(true)}
              style={{
                textAlign: 'center',
                cursor: 'pointer',
                borderBottom: '1px solid #f0f0f0',
                flexShrink: 0
              }}
            >
              <MenuFoldOutlined />
            </div>
            <div style={{ flex: 1, overflowY: 'auto', overflowX: 'hidden' }}>
              {renderSideMenu()}
            </div>
          </Sider>
        )}
        {collapsed && (
          <div
            className="menu-expand-toggle"
            onClick={() => setCollapsed(false)}
            style={{
              position: 'fixed',
              left: 0,
              top: '50%',
              transform: 'translateY(-50%)',
              width: '24px',
              height: '60px',
              background: '#fff',
              borderRadius: '0 4px 4px 0',
              boxShadow: '2px 0 8px rgba(0,0,0,0.15)',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              cursor: 'pointer',
              zIndex: 999
            }}
          >
            <MenuUnfoldOutlined />
          </div>
        )}
        <Content style={{
          margin: '16px',
          marginRight: '16px',
          marginBottom: 0,
          height: 'calc(100vh - 80px)',
          transition: 'all 0.2s',
          width: collapsed ? 'calc(100% - 40px)' : 'calc(100% - 248px)',
          marginLeft: collapsed ? '40px' : '248px',
          paddingBottom: 0,
          overflow: 'auto',
          background: 'transparent'
        }}>
          {customDialogVisable ? (
            <Drawer
              key="custom-dialog-drawer"
              getContainer={false}
              style={{ position: 'absolute', height: 'calc(100vh - 100px)', top: '10%', ...customDialogInfo?.style }}
              bodyStyle={{ padding: 0 }}
              mask={false}
              contentWrapperStyle={{ width: 'auto' }}
              title={customDialogInfo?.title}
              placement="right"
              onClose={() => setCustomDialogVisable(false)}
              visible={customDialogVisable}
            >
              <div className="h100" dangerouslySetInnerHTML={{ __html: customDialogInfo?.content || '' }}></div>
            </Drawer>
          ) : null}
          {isLoading ? (
            <div className="d-f jc ac h100">
              <Spin size="large" tip={t("正在加载应用...")} />
            </div>
          ) : (
            CurrentRouteComponent && <CurrentRouteComponent />
          )}
        </Content>
      </Layout>
      {customDialogInfo?.content ? (
        <div key="custom-dialog-button" className="c-text-w fs12 p-f" style={{ backgroundColor: 'transparent', zIndex: 10, right: 16, bottom: 32 }}>
          <div className="bg-theme d-f jc ac cp" style={{ borderRadius: 6, width: 36, height: 36 }} onClick={() => setCustomDialogVisable(true)}>
            <AppstoreOutlined style={{ color: '#fff', fontSize: 22 }} />
          </div>
        </div>
      ) : null}
    </Layout>
  );
};

export default AppWrapper;
